<template>
  <!-- 左侧列表栏区域 s-->
  <view class="uni-padding-wrap uni-common-mt">
    <view style="height: 100vh" v-if="!listGroup.length">
      <noData></noData>
    </view>
    <view v-else class="d-flex" style="display: flex">
      <scroll-view
        :show-scrollbar="false"
        scroll-with-animation
        :scroll-top="scrollTop"
        scroll-y="true"
        class="scroll-Y left-scroll"
        :scroll-into-view="rightScrollinto"
      >
        <view
          @click="changeIndex(index)"
          style="font-size: 26rpx"
          :id="'tab' + index"
          v-for="(item, index) in listGroup"
          :key="item.id"
          :class="currentIndex == index ? 'active-class' : ''"
        >
          {{ item.name }}
        </view>
      </scroll-view>
      <scroll-view
        :show-scrollbar="false"
        @scroll="rightscroll"
        scroll-with-animation
        :style="'height:' + scrollH + 'px'"
        :scroll-top="scrollTop"
        scroll-y="true"
        class="scroll-Y right-scroll"
        :scroll-into-view="leftScrollinto"
      >
        <view
          :id="'left' + bindex"
          v-for="(bitem, bindex) in listGroup"
          :key="bindex"
          class="d-flex flex-wrap demo3"
        >
          <view
            style="
              padding: 20rpx 0;
              position: sticky;
              left: 0;
              top: 0;
              background-color: #fff;
            "
            >{{ bitem.name }}</view
          >
          <view
            v-for="(childItem, Aindex) in bitem.children"
            :key="childItem.id"
            @click="handleItem(childItem)"
            class="scroll-view-item uni-bg-red goods-item"
          >
            <!-- <view
              class="img"
              :style="{
                backgroundImage: `url(${require('@/static/food-test.jpg')})`,
              }"
            > -->
            <view
              class="img"
              :style="{
                backgroundImage: `url(${foodFile + childItem.thumbnail})`,
              }"
            >
            </view>
            <view class="text infos">
              <view class="title">{{ childItem.name }}</view>
              <view class="remark">{{ childItem.remak || "" }}</view>
              <view class="price-add flex-between">
                <text class="price">{{
                  childItem.price ? `￥${childItem.price}` : ""
                }}</text>
                <view class="add-sub flex-between">
                  <view
                    v-if="cartList.some((val) => val.id === childItem.id)"
                    class="add-sub-btn flex-center sub-btn"
                    @click.stop="handleSub(childItem)"
                    >-</view
                  >
                  <text
                    style="margin: 0 20rpx"
                    v-if="cartList.some((val) => val.id === childItem.id)"
                    >{{
                      cartList.find((val) => val.id === childItem.id).number
                    }}</text
                  >
                  <view
                    class="add-sub-btn flex-center add-btn"
                    @click.stop="handleAdd(childItem)"
                    >+</view
                  >
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    <shopCart @openCart="openCart" />
    <uni-popup
      :is-mask-click="false"
      background-color="#ffffff"
      ref="codeRef"
      type="center"
      borderRadius="10px 10px 10px 10px"
    >
      <view class="code-pop">
        <view class="title" style="width: 100%; text-align: center">
          请选择点餐方式
        </view>
        <view class="center flex-between" @click="openCode">
          <view>
            <view class="center-title">扫码点餐</view>
            <view class="msg">请扫桌面上的二维码点餐</view>
          </view>
          <image
            style="width: 40rpx; height: 40rpx"
            :src="require('@/static/icon_right.png')"
            class="code-pop-icon"
          />
        </view>
        <view
          class="center flex-between"
          style="margin-top: 20rpx"
          @click="closeCode"
        >
          <view>
            <view class="center-title">直接点餐</view>
          </view>
          <image
            style="width: 40rpx; height: 40rpx"
            :src="require('@/static/icon_right.png')"
            class="code-pop-icon"
          />
        </view>
      </view>
    </uni-popup>
    <uni-popup
      :is-mask-click="false"
      background-color="#ffffff"
      ref="storeRef"
      type="center"
      borderRadius="10px 10px 10px 10px"
    >
      <view class="code-pop">
        <view class="title" style="width: 100%; text-align: center">
          请选择店铺
        </view>
        <view
          class="center flex-between"
          style="margin-top: 20rpx"
          v-for="(item, index) in storeList"
          :key="index"
          @click="confirmStore(item)"
        >
          <view>
            <view class="center-title">{{ item.name }}</view>
            <view class="msg">{{ item.appName }}</view>
          </view>
          <image
            style="width: 40rpx; height: 40rpx"
            :src="require('@/static/icon_right.png')"
            class="code-pop-icon"
          />
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
// import { getCate } from "../../api/cate.js";
import { foodList, chooseFoodTable, chooseStore } from "@/api/foodPage.js";
export default {
  data() {
    return {
      currentIndex: 0,
      listGroup: [],
      scrollH: 0,
      // 表明左右两侧滑动的标志scroll-into-view
      rightScrollinto: "",
      leftScrollinto: "",
      // 用一个数组承载每一个子区块的距离顶部的高度
      topList: [],
      tableNo: "",
      storeId: "",
      storeList: [],
      foodFile: uni.getStorageSync("foodFile"),
    };
  },
  mounted() {
    if (!this.tableNo) {
      this.$refs.codeRef.open();
    }
    // 使用定时器获取区块节点信息
    setTimeout(() => {
      this.getTop();
    }, 500);
  },
  onLoad(options) {
    if (options.tableNo) {
      this.codeIntoPage(options.tableNo);
    }
    this.getStoreInfo(options.storeId || "");
  },
  created() {
    // 异步获取系统信息，包括屏幕高度等
    const res = uni.getStorageSync("systemInfo", res);
    this.scrollH = res.windowHeight - uni.upx2px(156);
    console.log(res, "res================");

    // this.getCate();
  },
  computed: {
    cartList() {
      return this.$store.state.user.cartList;
    },
  },
  methods: {
    confirmStore(item) {
      this.storeId = item.id;
      uni.setStorageSync("storeId", item.id);
      this.getFoodsList();
      this.$store.dispatch("user/handleSetCardList", []);
      this.$refs.storeRef.close();
    },
    async getStoreInfo(storeId) {
      // 扫桌号进入
      if (storeId) {
        this.storeId = storeId;
        uni.setStorageSync("storeId", storeId);
        this.getFoodsList();
        return;
      }
      //直接点餐
      //获取店铺
      const { body } = await chooseStore({
        appCode: "FOOD",
        orgId: uni.getStorageSync("orgId"),
      });
      if (!body || body.length === 0) {
        return uni.showToast({
          title: "该机构暂无店铺",
          icon: "none",
        });
      }
      if (body && body.length === 1) {
        this.storeId = body[0].id;
        this.getFoodsList();
        return uni.setStorageSync("storeId", body[0].id);
      }
      this.storeList = body;
      this.$refs.storeRef.open();
    },
    // 扫码进入点餐
    async codeIntoPage(tableNo) {
      this.tableNo = tableNo;
      const result = await chooseFoodTable({
        orgId: uni.getStorageSync("orgId"),
      });
      const tableNoItem = (result.body || []).find((v) => v.tableNo == tableNo);
      if (!tableNoItem) {
        uni.showModal({
          title: "提示",
          content: "没有此桌号，请重新扫码",
          showCancel: false,
        });
        this.$nextTick(() => {
          this.$refs.codeRef.open();
        });
        return;
      }
      uni.setStorageSync("tableNo", tableNo);
    },
    closeCode() {
      this.$refs.codeRef.close();
      uni.setStorageSync("tableNo", "");
      this.tableNo = "";
    },
    openCode() {
      uni.scanCode({
        success: async (res) => {
          this.tableNo = res.result;
          const result = await chooseFoodTable({
            orgId: uni.getStorageSync("orgId"),
          });
          const tableNoItem = (result.body || []).find(
            (v) => v.tableNo == res.result
          );
          if (!tableNoItem) {
            return uni.showToast({
              title: "没有此桌号，请重新扫码",
              icon: "none",
            });
          }
          uni.setStorageSync("tableNo", res.result);
          this.$refs.codeRef.close();
        },
        fail(srr) {
          console.log("ss", srr);
        },
      });
    },
    handleItem(item) {
      uni.navigateTo({
        url: `/pages/foodPage/info?id=${item.id}`,
      });
    },
    handleAdd(item) {
      const cartList = this.cartList;
      const res = cartList.some((v) => v.id === item.id)
        ? cartList.map((v) => ({
            ...v,
            number: v.id === item.id ? (v.number || 0) + 1 : v.number,
          }))
        : [...cartList, { ...item, number: 1 }];
      this.$store.dispatch("user/handleSetCardList", res);
    },
    handleSub(item) {
      const cartList = this.cartList;
      const res = cartList
        .map((v) => ({
          ...v,
          number: item.id === v.id ? v.number - 1 : v.number,
        }))
        .filter((v) => v.number > 0);
      this.$store.dispatch("user/handleSetCardList", res);
    },
    // 调用获取分类页数据的方法
    getCate() {
      this.listGroup = [];
    },
    async getFoodsList() {
      const { body } = await foodList({
        pageSize: 9999,
        currentNum: 1,
        storeId: this.storeId,
      });
      const list = body.records || [];
      const res = list.reduce((pre, cur) => {
        if (pre[cur.groupId]) {
          pre[cur.groupId].children.push(cur);
        } else {
          pre[cur.groupId] = {
            name: cur.groupName,
            id: cur.groupId,
            children: [cur],
          };
        }
        return pre;
      }, {});
      const result = Object.values(res);
      this.listGroup = result;
      console.log(result, "result-------------");
    },
    // 左侧列表菜单的点击事件
    changeIndex(index) {
      this.currentIndex = index;
      this.rightScrollinto = "tab" + index;
      if (this.currentIndex < 6) {
        this.rightScrollinto = "tab0";
      }
      this.leftScrollinto = "left" + index;
    },
    // 获取右侧滑动区域每一个子区域的高度
    getTop() {
      const query = uni.createSelectorQuery().in(this);
      query
        .selectAll(".demo3")
        .boundingClientRect((data) => {
          // console.log("得到布局位置信息" + JSON.stringify(data));
          // console.log("节点离页面顶部的距离为" + data.top);
          if (data) {
            data.map((item, index) => {
              let top = index > 0 ? this.topList[index - 1] : 0;
              top += item.height;
              this.topList.push(top);
            });
          }
          console.log(this.topList);
        })
        .exec();
    },
    //右侧滑动区域的滑动事件
    rightscroll(event) {
      // console.log(event.target.scrollTop)
      let scrollTop = event.target.scrollTop;
      let result = this.topList.findIndex((item, index) => {
        return scrollTop < item;
      });
      // console.log(scrollTop, result, "--------------------------------------");
      this.currentIndex = result;
    },
  },
};
</script>

<style lang="scss" scoped>
.uni-padding-wrap {
  background-color: #fff;
}
.left-scroll {
  width: 200rpx;
  background: #f4f4f4;
  text-align: center;
}

.left-scroll view {
  padding: 30rpx;
}

.right-scroll {
  flex: 1;
  padding: 0 20rpx;
}

image {
  width: 120rpx;
  height: 120rpx;
}

.active-class {
  color: #5cc39d;
  background: white;
  border-top-right-radius: 10rpx;
  border-bottom-right-radius: 10rpx;
}
.d-flex {
  /* display: flex; */
}
.goods-item {
  display: flex;
  padding: 10rpx 0;
  .img {
    width: 180rpx;
    height: 180rpx;
    margin-right: 20rpx;
    background-color: #f2f2f2;
    border-radius: 10rpx;
    flex-shrink: 0;
    background-size: cover;
    background-repeat: no-repeat;
  }
  .infos {
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 10rpx 0;
    .title {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
    .remark {
      font-size: 20rpx;
      color: #666;
    }
    .price-add {
      .price {
        font-size: 30rpx;
        color: #da3946;
        font-weight: bold;
      }
      .add-sub-btn {
        width: 44rpx;
        height: 44rpx;
        line-height: 44rpx;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #5cc39d;
      }
      .sub-btn {
        background-color: #fff;
        border: 1px solid #5cc39d;
        line-height: 44rpx;
      }
      .add-btn {
        color: #fff;
      }
    }
  }
  .code-pop {
    width: 650rpx;
    background-color: #fff;
    border-radius: 40rpx;
    overflow: hidden;
    padding: 30rpx;
    .title {
      font-size: 36rpx;
      color: #999;
      margin: 20rpx 0;
      text-align: center;
      margin-bottom: 30rpx;
    }
    .center {
      padding: 30rpx 0;
      width: 100%;
      background-color: #5cc39d;
      border-radius: 50rpx;
      .center-title {
        font-size: 36rpx;
        color: #333;
        font-weight: bold;
      }
      .msg {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}
.page-index {
  overflow-y: hidden;
}
scroll-view ::-webkit-scrollbar {
  display: none;
  width: 0;
  height: 0;
  color: transparent;
}
.cart-pop {
  .title {
    display: flex;
    justify-content: flex-end;
  }
  .cart-content {
    .cart-img {
      width: 80rpx;
      height: 80rpx;
    }
  }
}
</style>
